package br.com.jk.cotacao.lancamento;

import br.com.jk.cotacao.*;
import br.com.jk.cliente.Cliente;
import br.com.jk.cliente.ClienteJDialog;
import br.com.jk.cotacao.itens.CotacaoItens;
import br.com.jk.cotacao.itens.CotacaoItensJDialog;
import br.com.jk.cotacao.itens.CotacaoItensRn;
import br.com.jk.empresa.Empresa;
import br.com.jk.empresa.EmpresaJDialog;
import br.com.jk.master.Master;
import br.com.jk.produto.Produto;
import br.com.jk.produto.ProdutoJDialog;
import br.com.jk.usuario.jtable.UsuarioJTableUtil;
import br.com.jk.util.ControllerException;
import br.com.jk.util.RNException;
import br.com.jk.util.StatusType.StatusEstoque;
import br.com.jk.util.Util;
import java.awt.event.KeyEvent;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.swing.JOptionPane;
import javax.swing.JTextField;

/**
 *
 * @author camilo
 */
public class CotacaoLancamentoJDialog extends javax.swing.JDialog {

  private static CotacaoLancamentoJDialog dialog;
  private Empresa filtroEmpresa;
  private Cotacao filtroCotacao;
  private Cliente filtroCliente;
  private CotacaoItens cotacaoItens;
  private Integer numLancamento;
  private Integer sequencial;
  // Model da tabela
  CotacaoLancamentoTableModel cotacaoLancamentoTm = new CotacaoLancamentoTableModel();
  CotacaoLancamentoController control = new CotacaoLancamentoController();
//  atributos utilizados nas pesquisas externas
  private JTextField idPesquisa;
  private JTextField razaoPesquisa;
  private boolean modoConsultaExt;

  public static CotacaoLancamentoJDialog getInstance(java.awt.Frame parent, boolean modal) {
    if (dialog == null) {
      dialog = new CotacaoLancamentoJDialog(parent, modal);
    }
    return dialog;
  }

  public static CotacaoLancamentoJDialog getInstance(java.awt.Frame parent, boolean modal, JTextField id, JTextField razao) {
    if (dialog == null) {
      dialog = new CotacaoLancamentoJDialog(parent, modal, id, razao);
    }
    return dialog;
  }

  /**
   * Creates new form FornecedorJDialog
   */
  private CotacaoLancamentoJDialog(java.awt.Frame parent, boolean modal) {
    super(parent, modal);
    initComponents();
    init();
  }

  private CotacaoLancamentoJDialog(java.awt.Frame parent, boolean modal, JTextField id, JTextField razao) {
    super(parent, modal);
    this.idPesquisa = id;
    this.razaoPesquisa = razao;
    this.modoConsultaExt = true;

    initComponents();
    init();
  }

  private void init() {
    criaModel();
    setLocationRelativeTo(null);
    jlFiltro.setVisible(false);
    numLancamento = control.ultimoNumLancamento();
    System.out.println(numLancamento);
  }

  private void criaModel() {
    jtCotacaoLancamento.setModel(cotacaoLancamentoTm);

    cotacaoLancamentoTm.sorter(jtCotacaoLancamento, cotacaoLancamentoTm);

    UsuarioJTableUtil.alteraJTable(cotacaoLancamentoTm, jtCotacaoLancamento, "jtCotacaoLancamento", Master.usuarioLogado);
  }

  /**
   * This method is called from within the constructor to initialize the form. WARNING: Do NOT modify this code. The
   * content of this method is always regenerated by the Form Editor.
   */
  @SuppressWarnings("unchecked")
  // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
  private void initComponents() {
    java.awt.GridBagConstraints gridBagConstraints;

    JtbMaster = new javax.swing.JToolBar();
    jbNovo = new javax.swing.JButton();
    JbSalvar = new javax.swing.JButton();
    JbEditar = new javax.swing.JButton();
    JbCancelar = new javax.swing.JButton();
    JbExcluir = new javax.swing.JButton();
    JbBuscar = new javax.swing.JButton();
    JbRelatorio = new javax.swing.JButton();
    jSeparator1 = new javax.swing.JToolBar.Separator();
    JbRefresh = new javax.swing.JButton();
    jlFiltro = new javax.swing.JLabel();
    jSeparator2 = new javax.swing.JToolBar.Separator();
    jbJTable = new javax.swing.JButton();
    jpFiltro = new javax.swing.JPanel();
    jLabel8 = new javax.swing.JLabel();
    jtfIdCliente = new javax.swing.JTextField();
    jtfNameCliente = new javax.swing.JTextField();
    jLabel9 = new javax.swing.JLabel();
    jtfIdCotacao = new javax.swing.JTextField();
    jtfNameCotacao = new javax.swing.JTextField();
    jLabel13 = new javax.swing.JLabel();
    jtfNameEmpresa = new javax.swing.JTextField();
    jtfIdEmpresa = new javax.swing.JTextField();
    jbFiltrar = new javax.swing.JButton();
    jLabel2 = new javax.swing.JLabel();
    jtfObservacao = new javax.swing.JTextField();
    jbReiniciar = new javax.swing.JButton();
    jScrollPane1 = new javax.swing.JScrollPane();
    jtCotacaoLancamento = new javax.swing.JTable();
    jpDados = new javax.swing.JPanel();
    jLabel1 = new javax.swing.JLabel();
    jtfQuantidade = new javax.swing.JTextField();
    jLabel3 = new javax.swing.JLabel();
    jtfValorCotado = new javax.swing.JTextField();
    jLabel5 = new javax.swing.JLabel();
    jtfIdProdutoVinculado = new javax.swing.JTextField();
    jLabel7 = new javax.swing.JLabel();
    jtfIdProduto = new javax.swing.JTextField();
    jtfNameProduto = new javax.swing.JTextField();
    jtfNameProdutoVinculado = new javax.swing.JTextField();
    jcbVinculado = new javax.swing.JCheckBox();
    jLabel11 = new javax.swing.JLabel();
    jtfFator = new javax.swing.JTextField();

    setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
    setTitle("COTAÇÃO - Lançamentos");
    addWindowListener(new java.awt.event.WindowAdapter() {
      public void windowClosed(java.awt.event.WindowEvent evt) {
        formWindowClosed(evt);
      }
    });

    JtbMaster.setRollover(true);

    jbNovo.setIcon(new javax.swing.ImageIcon(getClass().getResource("/br/com/jk/imagens/document-new.png"))); // NOI18N
    jbNovo.setToolTipText("Novo Registro");
    jbNovo.setEnabled(false);
    jbNovo.setFocusable(false);
    jbNovo.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
    jbNovo.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
    jbNovo.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent evt) {
        jbNovoActionPerformed(evt);
      }
    });
    JtbMaster.add(jbNovo);

    JbSalvar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/br/com/jk/imagens/document-save-hd.png"))); // NOI18N
    JbSalvar.setToolTipText("Salvar Registro");
    JbSalvar.setEnabled(false);
    JbSalvar.setFocusable(false);
    JbSalvar.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
    JbSalvar.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
    JbSalvar.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent evt) {
        JbSalvarActionPerformed(evt);
      }
    });
    JtbMaster.add(JbSalvar);

    JbEditar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/br/com/jk/imagens/document-edit.png"))); // NOI18N
    JbEditar.setToolTipText("Alterar registro");
    JbEditar.setEnabled(false);
    JbEditar.setFocusable(false);
    JbEditar.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
    JbEditar.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
    JbEditar.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent evt) {
        JbEditarActionPerformed(evt);
      }
    });
    JtbMaster.add(JbEditar);

    JbCancelar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/br/com/jk/imagens/dialog-cancel.png"))); // NOI18N
    JbCancelar.setToolTipText("Cancelar");
    JbCancelar.setEnabled(false);
    JbCancelar.setFocusable(false);
    JbCancelar.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
    JbCancelar.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
    JbCancelar.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent evt) {
        JbCancelarActionPerformed(evt);
      }
    });
    JtbMaster.add(JbCancelar);

    JbExcluir.setIcon(new javax.swing.ImageIcon(getClass().getResource("/br/com/jk/imagens/archive-remove.png"))); // NOI18N
    JbExcluir.setToolTipText("Excluir");
    JbExcluir.setEnabled(false);
    JbExcluir.setFocusable(false);
    JbExcluir.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
    JbExcluir.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
    JbExcluir.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent evt) {
        JbExcluirActionPerformed(evt);
      }
    });
    JtbMaster.add(JbExcluir);

    JbBuscar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/br/com/jk/imagens/edit-find.png"))); // NOI18N
    JbBuscar.setToolTipText("Buscar");
    JbBuscar.setEnabled(false);
    JbBuscar.setFocusable(false);
    JbBuscar.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
    JbBuscar.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
    JbBuscar.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent evt) {
        JbBuscarActionPerformed(evt);
      }
    });
    JtbMaster.add(JbBuscar);

    JbRelatorio.setIcon(new javax.swing.ImageIcon(getClass().getResource("/br/com/jk/imagens/report.png"))); // NOI18N
    JbRelatorio.setToolTipText("Relatórios");
    JbRelatorio.setEnabled(false);
    JbRelatorio.setFocusable(false);
    JbRelatorio.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
    JbRelatorio.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
    JbRelatorio.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent evt) {
        JbRelatorioActionPerformed(evt);
      }
    });
    JtbMaster.add(JbRelatorio);
    JtbMaster.add(jSeparator1);

    JbRefresh.setIcon(new javax.swing.ImageIcon(getClass().getResource("/br/com/jk/imagens/view-refresh.png"))); // NOI18N
    JbRefresh.setToolTipText("Atualizar registros da lista");
    JbRefresh.setFocusable(false);
    JbRefresh.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
    JbRefresh.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
    JbRefresh.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent evt) {
        JbRefreshActionPerformed(evt);
      }
    });
    JtbMaster.add(JbRefresh);

    jlFiltro.setIcon(new javax.swing.ImageIcon(getClass().getResource("/br/com/jk/imagens/task-attempt.png"))); // NOI18N
    JtbMaster.add(jlFiltro);
    JtbMaster.add(jSeparator2);

    jbJTable.setIcon(new javax.swing.ImageIcon(getClass().getResource("/br/com/jk/imagens/view-form-table.png"))); // NOI18N
    jbJTable.setToolTipText("Grava as informações da JTable");
    jbJTable.setFocusable(false);
    jbJTable.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
    jbJTable.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
    jbJTable.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent evt) {
        jbJTableActionPerformed(evt);
      }
    });
    JtbMaster.add(jbJTable);

    java.awt.GridBagLayout jpFiltroLayout = new java.awt.GridBagLayout();
    jpFiltroLayout.columnWidths = new int[] {50, 10, 150, 10, 50, 10, 150};
    jpFiltro.setLayout(jpFiltroLayout);

    jLabel8.setFont(new java.awt.Font("Liberation Sans", 0, 12)); // NOI18N
    jLabel8.setText("Cliente");
    gridBagConstraints = new java.awt.GridBagConstraints();
    gridBagConstraints.gridx = 4;
    gridBagConstraints.gridy = 0;
    gridBagConstraints.gridwidth = 2;
    gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST;
    jpFiltro.add(jLabel8, gridBagConstraints);

    jtfIdCliente.setFont(new java.awt.Font("Liberation Sans", 0, 12)); // NOI18N
    jtfIdCliente.addFocusListener(new java.awt.event.FocusAdapter() {
      public void focusLost(java.awt.event.FocusEvent evt) {
        jtfIdClienteFocusLost(evt);
      }
    });
    jtfIdCliente.addKeyListener(new java.awt.event.KeyAdapter() {
      public void keyPressed(java.awt.event.KeyEvent evt) {
        jtfIdClienteKeyPressed(evt);
      }
    });
    gridBagConstraints = new java.awt.GridBagConstraints();
    gridBagConstraints.gridx = 4;
    gridBagConstraints.gridy = 1;
    gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
    jpFiltro.add(jtfIdCliente, gridBagConstraints);

    jtfNameCliente.setEditable(false);
    jtfNameCliente.setFont(new java.awt.Font("Liberation Sans", 0, 12)); // NOI18N
    jtfNameCliente.setEnabled(false);
    gridBagConstraints = new java.awt.GridBagConstraints();
    gridBagConstraints.gridx = 6;
    gridBagConstraints.gridy = 1;
    gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
    jpFiltro.add(jtfNameCliente, gridBagConstraints);

    jLabel9.setFont(new java.awt.Font("Liberation Sans", 0, 12)); // NOI18N
    jLabel9.setText("Cotacao");
    gridBagConstraints = new java.awt.GridBagConstraints();
    gridBagConstraints.gridx = 0;
    gridBagConstraints.gridy = 2;
    gridBagConstraints.gridwidth = 2;
    gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST;
    jpFiltro.add(jLabel9, gridBagConstraints);

    jtfIdCotacao.setFont(new java.awt.Font("Liberation Sans", 0, 12)); // NOI18N
    jtfIdCotacao.setEnabled(false);
    jtfIdCotacao.addFocusListener(new java.awt.event.FocusAdapter() {
      public void focusLost(java.awt.event.FocusEvent evt) {
        jtfIdCotacaoFocusLost(evt);
      }
    });
    jtfIdCotacao.addKeyListener(new java.awt.event.KeyAdapter() {
      public void keyPressed(java.awt.event.KeyEvent evt) {
        jtfIdCotacaoKeyPressed(evt);
      }
    });
    gridBagConstraints = new java.awt.GridBagConstraints();
    gridBagConstraints.gridx = 0;
    gridBagConstraints.gridy = 3;
    gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
    jpFiltro.add(jtfIdCotacao, gridBagConstraints);

    jtfNameCotacao.setEditable(false);
    jtfNameCotacao.setFont(new java.awt.Font("Liberation Sans", 0, 12)); // NOI18N
    jtfNameCotacao.setEnabled(false);
    gridBagConstraints = new java.awt.GridBagConstraints();
    gridBagConstraints.gridx = 2;
    gridBagConstraints.gridy = 3;
    gridBagConstraints.gridwidth = 5;
    gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
    jpFiltro.add(jtfNameCotacao, gridBagConstraints);

    jLabel13.setFont(new java.awt.Font("Liberation Sans", 0, 12)); // NOI18N
    jLabel13.setText("Empresa");
    gridBagConstraints = new java.awt.GridBagConstraints();
    gridBagConstraints.gridx = 0;
    gridBagConstraints.gridy = 0;
    jpFiltro.add(jLabel13, gridBagConstraints);

    jtfNameEmpresa.setEditable(false);
    jtfNameEmpresa.setFont(new java.awt.Font("Liberation Sans", 0, 12)); // NOI18N
    jtfNameEmpresa.setEnabled(false);
    gridBagConstraints = new java.awt.GridBagConstraints();
    gridBagConstraints.gridx = 2;
    gridBagConstraints.gridy = 1;
    gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
    jpFiltro.add(jtfNameEmpresa, gridBagConstraints);

    jtfIdEmpresa.setFont(new java.awt.Font("Liberation Sans", 0, 12)); // NOI18N
    jtfIdEmpresa.addFocusListener(new java.awt.event.FocusAdapter() {
      public void focusLost(java.awt.event.FocusEvent evt) {
        jtfIdEmpresaFocusLost(evt);
      }
    });
    jtfIdEmpresa.addKeyListener(new java.awt.event.KeyAdapter() {
      public void keyPressed(java.awt.event.KeyEvent evt) {
        jtfIdEmpresaKeyPressed(evt);
      }
    });
    gridBagConstraints = new java.awt.GridBagConstraints();
    gridBagConstraints.gridx = 0;
    gridBagConstraints.gridy = 1;
    gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
    jpFiltro.add(jtfIdEmpresa, gridBagConstraints);

    jbFiltrar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/br/com/jk/imagens/dialog-ok.png"))); // NOI18N
    jbFiltrar.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent evt) {
        jbFiltrarActionPerformed(evt);
      }
    });
    gridBagConstraints = new java.awt.GridBagConstraints();
    gridBagConstraints.gridx = 7;
    gridBagConstraints.gridy = 3;
    jpFiltro.add(jbFiltrar, gridBagConstraints);

    jLabel2.setText("Observação");
    gridBagConstraints = new java.awt.GridBagConstraints();
    gridBagConstraints.gridx = 0;
    gridBagConstraints.gridy = 4;
    jpFiltro.add(jLabel2, gridBagConstraints);

    jtfObservacao.setEnabled(false);
    jtfObservacao.addKeyListener(new java.awt.event.KeyAdapter() {
      public void keyPressed(java.awt.event.KeyEvent evt) {
        jtfObservacaoKeyPressed(evt);
      }
    });
    gridBagConstraints = new java.awt.GridBagConstraints();
    gridBagConstraints.gridx = 0;
    gridBagConstraints.gridy = 5;
    gridBagConstraints.gridwidth = 7;
    gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
    jpFiltro.add(jtfObservacao, gridBagConstraints);

    jbReiniciar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/br/com/jk/imagens/edit-undo.png"))); // NOI18N
    jbReiniciar.setToolTipText("Reiniciar");
    jbReiniciar.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent evt) {
        jbReiniciarActionPerformed(evt);
      }
    });
    gridBagConstraints = new java.awt.GridBagConstraints();
    gridBagConstraints.gridx = 7;
    gridBagConstraints.gridy = 5;
    jpFiltro.add(jbReiniciar, gridBagConstraints);

    /*jtCotacaoLancamento.getSelectionModel().addListSelectionListener(new ListSelectionListener(){
      public void valueChanged(ListSelectionEvent evt){
        if (evt.getValueIsAdjusting()){
          return;
        }
        int selected = jtCotacaoLancamento.getSelectedRow();
        fControl.selecionado();
      }
    });

    jtCotacaoLancamento.getColumnModel().getSelectionModel().addListSelectionListener(new ListSelectionListener(){
      public void valueChanged(ListSelectionEvent evt){
        if (evt.getValueIsAdjusting()){
          return;
        }
        int selected = jtCotacaoLancamento.getSelectedColumn();
        fControl.selecionado();
      }
    });*/
    jtCotacaoLancamento.setAutoResizeMode(javax.swing.JTable.AUTO_RESIZE_OFF);
    jtCotacaoLancamento.addMouseListener(new java.awt.event.MouseAdapter() {
      public void mouseClicked(java.awt.event.MouseEvent evt) {
        jtCotacaoLancamentoMouseClicked(evt);
      }
    });
    jtCotacaoLancamento.addKeyListener(new java.awt.event.KeyAdapter() {
      public void keyPressed(java.awt.event.KeyEvent evt) {
        jtCotacaoLancamentoKeyPressed(evt);
      }
    });
    jScrollPane1.setViewportView(jtCotacaoLancamento);

    jpDados.setBorder(javax.swing.BorderFactory.createTitledBorder(javax.swing.BorderFactory.createTitledBorder(""), "Dados"));
    java.awt.GridBagLayout jpDadosLayout = new java.awt.GridBagLayout();
    jpDadosLayout.columnWidths = new int[] {100, 20, 100, 190, 20, 100};
    jpDadosLayout.columnWeights = new double[] {0.0};
    jpDados.setLayout(jpDadosLayout);

    jLabel1.setFont(new java.awt.Font("Liberation Sans", 0, 14)); // NOI18N
    jLabel1.setText("Quantidade");
    gridBagConstraints = new java.awt.GridBagConstraints();
    gridBagConstraints.gridx = 0;
    gridBagConstraints.gridy = 2;
    gridBagConstraints.gridwidth = 2;
    gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
    jpDados.add(jLabel1, gridBagConstraints);

    jtfQuantidade.setFont(new java.awt.Font("Liberation Sans", 0, 14)); // NOI18N
    jtfQuantidade.setEnabled(false);
    jtfQuantidade.addKeyListener(new java.awt.event.KeyAdapter() {
      public void keyPressed(java.awt.event.KeyEvent evt) {
        jtfQuantidadeKeyPressed(evt);
      }
    });
    gridBagConstraints = new java.awt.GridBagConstraints();
    gridBagConstraints.gridx = 0;
    gridBagConstraints.gridy = 3;
    gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
    jpDados.add(jtfQuantidade, gridBagConstraints);

    jLabel3.setFont(new java.awt.Font("Liberation Sans", 0, 14)); // NOI18N
    jLabel3.setText("Valor Cotado");
    gridBagConstraints = new java.awt.GridBagConstraints();
    gridBagConstraints.gridx = 2;
    gridBagConstraints.gridy = 2;
    gridBagConstraints.gridwidth = 2;
    gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
    jpDados.add(jLabel3, gridBagConstraints);

    jtfValorCotado.setFont(new java.awt.Font("Liberation Sans", 0, 14)); // NOI18N
    jtfValorCotado.setEnabled(false);
    jtfValorCotado.addKeyListener(new java.awt.event.KeyAdapter() {
      public void keyPressed(java.awt.event.KeyEvent evt) {
        jtfValorCotadoKeyPressed(evt);
      }
    });
    gridBagConstraints = new java.awt.GridBagConstraints();
    gridBagConstraints.gridx = 2;
    gridBagConstraints.gridy = 3;
    gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
    jpDados.add(jtfValorCotado, gridBagConstraints);

    jLabel5.setFont(new java.awt.Font("Liberation Sans", 0, 14)); // NOI18N
    jLabel5.setText("Produto Vinculado");
    gridBagConstraints = new java.awt.GridBagConstraints();
    gridBagConstraints.gridx = 0;
    gridBagConstraints.gridy = 4;
    gridBagConstraints.gridwidth = 3;
    gridBagConstraints.anchor = java.awt.GridBagConstraints.LAST_LINE_START;
    jpDados.add(jLabel5, gridBagConstraints);

    jtfIdProdutoVinculado.setFont(new java.awt.Font("Liberation Sans", 0, 14)); // NOI18N
    jtfIdProdutoVinculado.setEnabled(false);
    jtfIdProdutoVinculado.addKeyListener(new java.awt.event.KeyAdapter() {
      public void keyPressed(java.awt.event.KeyEvent evt) {
        jtfIdProdutoVinculadoKeyPressed(evt);
      }
    });
    gridBagConstraints = new java.awt.GridBagConstraints();
    gridBagConstraints.gridx = 0;
    gridBagConstraints.gridy = 5;
    gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
    jpDados.add(jtfIdProdutoVinculado, gridBagConstraints);

    jLabel7.setFont(new java.awt.Font("Liberation Sans", 0, 14)); // NOI18N
    jLabel7.setText("Produto");
    gridBagConstraints = new java.awt.GridBagConstraints();
    gridBagConstraints.gridx = 0;
    gridBagConstraints.gridy = 0;
    gridBagConstraints.gridwidth = 2;
    gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
    jpDados.add(jLabel7, gridBagConstraints);

    jtfIdProduto.setFont(new java.awt.Font("Liberation Sans", 0, 14)); // NOI18N
    jtfIdProduto.setEnabled(false);
    jtfIdProduto.addKeyListener(new java.awt.event.KeyAdapter() {
      public void keyPressed(java.awt.event.KeyEvent evt) {
        jtfIdProdutoKeyPressed(evt);
      }
    });
    gridBagConstraints = new java.awt.GridBagConstraints();
    gridBagConstraints.gridx = 0;
    gridBagConstraints.gridy = 1;
    gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
    jpDados.add(jtfIdProduto, gridBagConstraints);

    jtfNameProduto.setEditable(false);
    jtfNameProduto.setFont(new java.awt.Font("Liberation Sans", 0, 14)); // NOI18N
    jtfNameProduto.setEnabled(false);
    gridBagConstraints = new java.awt.GridBagConstraints();
    gridBagConstraints.gridx = 2;
    gridBagConstraints.gridy = 1;
    gridBagConstraints.gridwidth = 2;
    gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
    jpDados.add(jtfNameProduto, gridBagConstraints);

    jtfNameProdutoVinculado.setFont(new java.awt.Font("Liberation Sans", 0, 14)); // NOI18N
    jtfNameProdutoVinculado.setEnabled(false);
    gridBagConstraints = new java.awt.GridBagConstraints();
    gridBagConstraints.gridx = 2;
    gridBagConstraints.gridy = 5;
    gridBagConstraints.gridwidth = 2;
    gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
    jpDados.add(jtfNameProdutoVinculado, gridBagConstraints);

    jcbVinculado.setFont(new java.awt.Font("Liberation Sans", 0, 14)); // NOI18N
    jcbVinculado.setText("Vinculado");
    jcbVinculado.setEnabled(false);
    jcbVinculado.addKeyListener(new java.awt.event.KeyAdapter() {
      public void keyPressed(java.awt.event.KeyEvent evt) {
        jcbVinculadoKeyPressed(evt);
      }
    });
    gridBagConstraints = new java.awt.GridBagConstraints();
    gridBagConstraints.gridx = 3;
    gridBagConstraints.gridy = 4;
    gridBagConstraints.anchor = java.awt.GridBagConstraints.LINE_END;
    jpDados.add(jcbVinculado, gridBagConstraints);

    jLabel11.setFont(new java.awt.Font("Liberation Sans", 0, 14)); // NOI18N
    jLabel11.setText("Fator");
    gridBagConstraints = new java.awt.GridBagConstraints();
    gridBagConstraints.gridx = 5;
    gridBagConstraints.gridy = 4;
    gridBagConstraints.anchor = java.awt.GridBagConstraints.LAST_LINE_START;
    jpDados.add(jLabel11, gridBagConstraints);

    jtfFator.setFont(new java.awt.Font("Liberation Sans", 0, 14)); // NOI18N
    jtfFator.setEnabled(false);
    jtfFator.addKeyListener(new java.awt.event.KeyAdapter() {
      public void keyPressed(java.awt.event.KeyEvent evt) {
        jtfFatorKeyPressed(evt);
      }
    });
    gridBagConstraints = new java.awt.GridBagConstraints();
    gridBagConstraints.gridx = 5;
    gridBagConstraints.gridy = 5;
    gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
    jpDados.add(jtfFator, gridBagConstraints);

    javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
    getContentPane().setLayout(layout);
    layout.setHorizontalGroup(
      layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
      .addGroup(layout.createSequentialGroup()
        .addGap(4, 4, 4)
        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
          .addComponent(jpDados, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE)
          .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 578, Short.MAX_VALUE)))
      .addComponent(JtbMaster, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
      .addGroup(layout.createSequentialGroup()
        .addContainerGap()
        .addComponent(jpFiltro, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        .addContainerGap())
    );
    layout.setVerticalGroup(
      layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
      .addGroup(layout.createSequentialGroup()
        .addComponent(JtbMaster, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE)
        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
        .addComponent(jpFiltro, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
        .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 210, Short.MAX_VALUE)
        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
        .addComponent(jpDados, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
        .addGap(13, 13, 13))
    );

    pack();
  }// </editor-fold>//GEN-END:initComponents

  private void jbNovoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbNovoActionPerformed
    novo();
  }//GEN-LAST:event_jbNovoActionPerformed

  private void JbSalvarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_JbSalvarActionPerformed
    salvar();
  }//GEN-LAST:event_JbSalvarActionPerformed

  private void JbEditarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_JbEditarActionPerformed
    editar();
  }//GEN-LAST:event_JbEditarActionPerformed

  private void JbCancelarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_JbCancelarActionPerformed
    cancelar();
  }//GEN-LAST:event_JbCancelarActionPerformed

  private void JbExcluirActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_JbExcluirActionPerformed
    excluir();
  }//GEN-LAST:event_JbExcluirActionPerformed

  private void JbBuscarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_JbBuscarActionPerformed
    control.pesquisar();
  }//GEN-LAST:event_JbBuscarActionPerformed

  private void JbRelatorioActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_JbRelatorioActionPerformed
    try {
//      Master.setJpbStatusIndeterminate(true);
//      Master.setTextJlStatus("Gerando relatório...");
      ThreadReport thReport = new ThreadReport();
      thReport.start();

    } catch (Exception e) {
      Util.msgErro(e, "Erro ao gerar o relatório");
    }
  }//GEN-LAST:event_JbRelatorioActionPerformed

  private void JbRefreshActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_JbRefreshActionPerformed
    listar();
    jlFiltro.setVisible(false);
    JbBuscar.setEnabled(false);
  }//GEN-LAST:event_JbRefreshActionPerformed

  private void jtCotacaoLancamentoMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jtCotacaoLancamentoMouseClicked
    if (cotacaoLancamentoTm.getRowCount() > 0 && (jtfValorCotado != null)) {
      habilitaJb(true, false, true, false, true);
      habilitaJtf(false);
      limpar();
      selecionado();
    }
  }//GEN-LAST:event_jtCotacaoLancamentoMouseClicked

  private void jtfQuantidadeKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jtfQuantidadeKeyPressed
    if (evt.getKeyCode() == KeyEvent.VK_ENTER) {
      adicionaItem();
    }
  }//GEN-LAST:event_jtfQuantidadeKeyPressed

  private void jtfValorCotadoKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jtfValorCotadoKeyPressed
    if (evt.getKeyCode() == KeyEvent.VK_ENTER) {
      jtfQuantidade.requestFocus();
    }
  }//GEN-LAST:event_jtfValorCotadoKeyPressed

  private void jtfIdProdutoVinculadoKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jtfIdProdutoVinculadoKeyPressed
    if (evt.getKeyCode() == KeyEvent.VK_ENTER) {
      if (jtfIdProdutoVinculado.getText().isEmpty()) {
        selecionaItem(jtfIdProdutoVinculado, jtfNameProdutoVinculado);
        jtfFator.requestFocus();
      } else {
        try {
          CotacaoItens prod = control.carregaCotacaoItem(Integer.parseInt(jtfIdProdutoVinculado.getText()));
          jtfIdProdutoVinculado.setText(String.valueOf(prod.getProdutoVinculado().getId()));
          jtfNameProdutoVinculado.setText(prod.getProdutoVinculado().getDescricao());
        } catch (NullPointerException e) {
          Util.msgAdv(e, "Não foi localizado nenhum produto para o id informado.");
        }
        jtfFator.requestFocus();
      }
    } else if (evt.getKeyCode() == KeyEvent.VK_F12) {
      selecionaItem(jtfIdProdutoVinculado, jtfNameProdutoVinculado);
    }
  }//GEN-LAST:event_jtfIdProdutoVinculadoKeyPressed

  private void jtfIdProdutoKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jtfIdProdutoKeyPressed
    if (evt.getKeyCode() == KeyEvent.VK_ENTER) {
      if (jtfIdProduto.getText().isEmpty()) {
        selecionaItem(jtfIdProduto, jtfNameProduto);
      } else if (jtfNameProduto.getText().isEmpty()) {
        try {
          cotacaoItens = control.carregaCotacaoItem(Integer.parseInt(jtfIdProduto.getText()));
          jtfIdProduto.setText(String.valueOf(cotacaoItens.getProduto().getId()));
          jtfNameProduto.setText(cotacaoItens.getProduto().getDescricao());
        } catch (NullPointerException e) {
          Util.msgAdv(e, "Não foi localizado nenhum produto para o id informado.");
        }
      }
      jtfQuantidade.requestFocus();
    } else if (evt.getKeyCode() == KeyEvent.VK_F12) {
      selecionaItem(jtfIdProduto, jtfNameProduto);
      cotacaoItens = control.carregaCotacaoItem(Integer.parseInt(jtfIdProduto.getText()));
    }
  }//GEN-LAST:event_jtfIdProdutoKeyPressed

  private void jtCotacaoLancamentoKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jtCotacaoLancamentoKeyPressed
    if (evt.getKeyCode() == KeyEvent.VK_SPACE) {
      if (JbBuscar.isEnabled()) {
        control.pesquisar();
      }
    } else if (evt.getKeyCode() == KeyEvent.VK_ENTER) {
      if (modoConsultaExt) {
        selecionaRegistro();
      }
    }
  }//GEN-LAST:event_jtCotacaoLancamentoKeyPressed

  private void formWindowClosed(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosed
    dialog = null;
  }//GEN-LAST:event_formWindowClosed

  private void jtfIdEmpresaKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jtfIdEmpresaKeyPressed
    if (evt.getKeyCode() == KeyEvent.VK_ENTER) {
      carregaEmpresa(jtfIdEmpresa, jtfNameEmpresa);
      habilitaSelectCotacao();
    } else if (evt.getKeyCode() == KeyEvent.VK_F12) {
      EmpresaJDialog.getInstance(null, true, jtfIdEmpresa, jtfNameEmpresa).setVisible(true);
      habilitaSelectCotacao();
    }
  }//GEN-LAST:event_jtfIdEmpresaKeyPressed

  private void jtfIdClienteKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jtfIdClienteKeyPressed
    if (evt.getKeyCode() == KeyEvent.VK_ENTER) {
      carregaCliente(jtfIdCliente, jtfNameCliente);
      habilitaSelectCotacao();
    } else if (evt.getKeyCode() == KeyEvent.VK_F12) {
      ClienteJDialog.getInstance(null, true, jtfIdCliente, jtfNameCliente).setVisible(true);
      habilitaSelectCotacao();
    }
  }//GEN-LAST:event_jtfIdClienteKeyPressed

  private void jtfIdCotacaoKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jtfIdCotacaoKeyPressed
    if (evt.getKeyCode() == KeyEvent.VK_ENTER) {
      carregaCotacao(jtfIdCotacao, jtfNameCotacao);
      habilitaSelectCotacao();
    } else if (evt.getKeyCode() == KeyEvent.VK_F12) {
      CotacaoJDialog.getInstance(null, true, jtfIdCotacao, jtfNameCotacao,
              filtroEmpresa, filtroCliente).setVisible(true);
      habilitaSelectCotacao();
    }
  }//GEN-LAST:event_jtfIdCotacaoKeyPressed

  private void jbFiltrarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbFiltrarActionPerformed
    filtroInicio();
  }//GEN-LAST:event_jbFiltrarActionPerformed

  private void jtfIdEmpresaFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_jtfIdEmpresaFocusLost
    carregaEmpresa(jtfIdEmpresa, jtfNameEmpresa);
  }//GEN-LAST:event_jtfIdEmpresaFocusLost

  private void jtfIdClienteFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_jtfIdClienteFocusLost
    carregaCliente(jtfIdCliente, jtfNameCliente);
  }//GEN-LAST:event_jtfIdClienteFocusLost

  private void jtfIdCotacaoFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_jtfIdCotacaoFocusLost
    carregaCotacao(jtfIdCotacao, jtfNameCotacao);
  }//GEN-LAST:event_jtfIdCotacaoFocusLost

  private void jcbVinculadoKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jcbVinculadoKeyPressed
    if (evt.getKeyCode() == KeyEvent.VK_ENTER) {
      if (jcbVinculado.isSelected()) {
        habilitaEdicaoVinculado(true);
        jtfIdProdutoVinculado.requestFocus();
      } else {
        salvar();
      }
    }
  }//GEN-LAST:event_jcbVinculadoKeyPressed

  private void jtfFatorKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jtfFatorKeyPressed
    if (evt.getKeyCode() == KeyEvent.VK_ENTER) {
      salvar();
    }
  }//GEN-LAST:event_jtfFatorKeyPressed

  private void jtfObservacaoKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jtfObservacaoKeyPressed
    if (evt.getKeyCode() == KeyEvent.VK_ENTER) {
      jtfIdProduto.requestFocus();
    }
  }//GEN-LAST:event_jtfObservacaoKeyPressed

  private void jbJTableActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbJTableActionPerformed
    getLarguraJtBanco();
  }//GEN-LAST:event_jbJTableActionPerformed

  private void jbReiniciarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbReiniciarActionPerformed
    reiniciar();
  }//GEN-LAST:event_jbReiniciarActionPerformed

  /**
   * @param args the command line arguments
   */
  public static void main(String args[]) {
    /* Set the Nimbus look and feel */
    //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
     * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
     */
    try {
      for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
        if ("Nimbus".equals(info.getName())) {
          javax.swing.UIManager.setLookAndFeel(info.getClassName());
          break;
        }
      }
    } catch (ClassNotFoundException ex) {
      java.util.logging.Logger.getLogger(CotacaoLancamentoJDialog.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (InstantiationException ex) {
      java.util.logging.Logger.getLogger(CotacaoLancamentoJDialog.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (IllegalAccessException ex) {
      java.util.logging.Logger.getLogger(CotacaoLancamentoJDialog.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (javax.swing.UnsupportedLookAndFeelException ex) {
      java.util.logging.Logger.getLogger(CotacaoLancamentoJDialog.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    }
    //</editor-fold>

    /* Create and display the dialog */
    java.awt.EventQueue.invokeLater(new Runnable() {
      @Override
      public void run() {
        CotacaoLancamentoJDialog dialog = new CotacaoLancamentoJDialog(new javax.swing.JFrame(), true);
        dialog.addWindowListener(new java.awt.event.WindowAdapter() {
          @Override
          public void windowClosing(java.awt.event.WindowEvent e) {
            System.exit(0);
          }
        });
        dialog.setVisible(true);
      }
    });
  }
  // Variables declaration - do not modify//GEN-BEGIN:variables
  private javax.swing.JButton JbBuscar;
  private javax.swing.JButton JbCancelar;
  private javax.swing.JButton JbEditar;
  private javax.swing.JButton JbExcluir;
  private javax.swing.JButton JbRefresh;
  private javax.swing.JButton JbRelatorio;
  private javax.swing.JButton JbSalvar;
  private javax.swing.JToolBar JtbMaster;
  private javax.swing.JLabel jLabel1;
  private javax.swing.JLabel jLabel11;
  private javax.swing.JLabel jLabel13;
  private javax.swing.JLabel jLabel2;
  private javax.swing.JLabel jLabel3;
  private javax.swing.JLabel jLabel5;
  private javax.swing.JLabel jLabel7;
  private javax.swing.JLabel jLabel8;
  private javax.swing.JLabel jLabel9;
  private javax.swing.JScrollPane jScrollPane1;
  private javax.swing.JToolBar.Separator jSeparator1;
  private javax.swing.JToolBar.Separator jSeparator2;
  private javax.swing.JButton jbFiltrar;
  private javax.swing.JButton jbJTable;
  private javax.swing.JButton jbNovo;
  private javax.swing.JButton jbReiniciar;
  private javax.swing.JCheckBox jcbVinculado;
  private javax.swing.JLabel jlFiltro;
  private javax.swing.JPanel jpDados;
  private javax.swing.JPanel jpFiltro;
  private javax.swing.JTable jtCotacaoLancamento;
  private javax.swing.JTextField jtfFator;
  private javax.swing.JTextField jtfIdCliente;
  private javax.swing.JTextField jtfIdCotacao;
  private javax.swing.JTextField jtfIdEmpresa;
  private javax.swing.JTextField jtfIdProduto;
  private javax.swing.JTextField jtfIdProdutoVinculado;
  private javax.swing.JTextField jtfNameCliente;
  private javax.swing.JTextField jtfNameCotacao;
  private javax.swing.JTextField jtfNameEmpresa;
  private javax.swing.JTextField jtfNameProduto;
  private javax.swing.JTextField jtfNameProdutoVinculado;
  private javax.swing.JTextField jtfObservacao;
  private javax.swing.JTextField jtfQuantidade;
  private javax.swing.JTextField jtfValorCotado;
  // End of variables declaration//GEN-END:variables
  Util.ValidaDigitacaoData docDataCadastro = new Util().new ValidaDigitacaoData();

  public void novo() {
    limpar();
    habilitaJb(false, true, false, true, false);
    habilitaJtf(true);

    jtfIdProduto.requestFocus();
  }

  private void getLarguraJtBanco() {
    UsuarioJTableUtil.setUsuarioJTable(cotacaoLancamentoTm, jtCotacaoLancamento, "jtCotacaoLancamento", Master.usuarioLogado);
  }

  private void selecionaEmpresa() {
    EmpresaJDialog.getInstance(null, true, jtfIdProduto, jtfNameProduto).setVisible(true);
  }

  private void selecionaCliente() {
    ClienteJDialog.getInstance(null, true, jtfIdProdutoVinculado, jtfNameProdutoVinculado).setVisible(true);
  }

  private void selecionaItem(JTextField jtfId, JTextField jtfName) {
    CotacaoItensJDialog.getInstance(null, true, jtfId, jtfName, filtroEmpresa, filtroCliente, filtroCotacao).setVisible(true);

  }

  public void selecionado() {
    int linha = jtCotacaoLancamento.getSelectedRow();//grava a linha selecionada
    int linhaSel = jtCotacaoLancamento.convertRowIndexToModel(linha);

    if (linhaSel >= 0) { // executa o procedimento se o JTable não estiver vazio
      int colunaSel = jtCotacaoLancamento.getSelectedColumn(); //grava a coluna selecionada
      boolean pesq = control.setEnabledPesquisa(colunaSel); // Verifica as colunas que serão habilitadas para pesquisa
      jtfQuantidade.setText(cotacaoLancamentoTm.getValueAt(linhaSel, CotacaoLancamentoTableModel.COLUNA_COD_QUANTIDADE).toString());
      jtfValorCotado.setText(cotacaoLancamentoTm.getValueAt(linhaSel, CotacaoLancamentoTableModel.COLUNA_COD_VALOR_COTADO).toString());
      jtfIdProduto.setText(cotacaoLancamentoTm.getValueAt(linhaSel, CotacaoLancamentoTableModel.COLUNA_COD_ID_PRODUTO).toString());
//    jtfIdProdutoVinculado.setText(cotacaoLancamentoTm.getValueAt(linhaSel, CotacaoLancamentoTableModel.COLUNA_COD_).toString());
      sequencial = Integer.parseInt(cotacaoLancamentoTm.getValueAt(linhaSel, CotacaoLancamentoTableModel.COLUNA_COD_SEQUENCIAL).toString());

      control.modoConsulta = pesq;
      JbBuscar.setEnabled(pesq);
    }
  }

  public List<CotacaoLancamento> criaObjetos() {
    List<CotacaoLancamento> itens = new ArrayList<>();
    for (int i = 0; i < cotacaoLancamentoTm.getRowCount(); i++) {
      jtCotacaoLancamento.setRowSelectionInterval(i, i);
      selecionado();
      itens.add(criaObjeto());
    }
    return itens;
  }

  public CotacaoLancamento criaObjeto() {
    CotacaoLancamento cotLancamento = new CotacaoLancamento();
    cotLancamento.setCotacao(filtroCotacao);

    try {
      Produto produto = control.carregaProduto(Integer.parseInt(jtfIdProduto.getText()));
      cotLancamento.setProduto(produto);
    } catch (NullPointerException e) {
      Util.msgErro("O Id da Empresa é inválido");
    }
    cotLancamento.setQuantidade(Integer.parseInt(jtfQuantidade.getText()));
    cotLancamento.setCotacaoItens(cotacaoItens);
    cotLancamento.setDataLancamento(new Date(System.currentTimeMillis()));
    cotLancamento.setNumLancamento(numLancamento);
    if (sequencial != null) {
      cotLancamento.setSequencial(sequencial);
    }

    return cotLancamento;
  }

  private void salvar() {
    try {
      List<CotacaoLancamento> cotLanc = criaObjetos();

      for (int i = 0; i < cotLanc.size(); i++) {
        control.salvar(cotLanc.get(i));
      }

      habilitaJb(true, false, false, false, false);
      habilitaJtf(false);

      reiniciar();

      Util.msgInfo("Lancamento nº " + numLancamento);
    } catch (ControllerException e) {
      Util.msgErro(e);
    }
  }

  private void adicionaItem() {
    CotacaoLancamento cot = criaObjeto();
    if (validaQuantidade(cot)) {
      cotacaoLancamentoTm.adiciona(cot);
      limpar();
      habilitaJtf(false);
      if (JOptionPane.showConfirmDialog(null, "Cadastrar outro item?", "Adiciona Item", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE)
              == JOptionPane.OK_OPTION) {
        novo();
      }
    }
  }

  private Boolean validaQuantidade(CotacaoLancamento cot) {
    CotacaoLancamentoRn cotRn = new CotacaoLancamentoRn();
    try {
      return cotRn.validaQuantidade(cot);
    } catch (RNException e) {
      Util.msgAdv(e);
    }
    return false;
  }

  private void listar() {
    setJtCotacaoTm(control.listar(numLancamento));
    limpar();
  }

  private void limparFiltro() {
    filtroCliente = null;
    filtroCotacao = null;
    filtroEmpresa = null;
    jtfIdCliente.setText(null);
    jtfNameCliente.setText(null);
    jtfIdCotacao.setText(null);
    jtfNameCotacao.setText(null);
    jtfIdEmpresa.setText(null);
    jtfNameEmpresa.setText(null);
  }

  private void limpar() {
    jtfQuantidade.setText(null);
    jtfValorCotado.setText(null);
    jtfNameProduto.setText(null);
    jtfIdProduto.setText(null);
    jtfIdProdutoVinculado.setText(null);
    JbBuscar.setEnabled(false);
  }

  public void setJtCotacaoTm(List<CotacaoLancamento> ct) {
    removeAllJtable();
    if (!ct.isEmpty()) {
      cotacaoLancamentoTm.adicionaLista(ct);
    }
  }

  public void setJtCotacaoTm(CotacaoLancamento ct) {
    removeAllJtable();
    if (ct != null) {
      cotacaoLancamentoTm.adiciona(ct);
    }
  }

  private void removeAllJtable() {
    while (cotacaoLancamentoTm.getRowCount() > 0) {
      cotacaoLancamentoTm.remove(0);
    }
  }

  /**
   * Determina quais os botões da barra de ferramentas ficará ativo
   *
   * @param novo
   * @param salvar
   * @param editar
   * @param cancelar
   * @param excluir
   */
  public void habilitaJb(Boolean novo, Boolean salvar, Boolean editar, Boolean cancelar,
          Boolean excluir) {
    jbNovo.setEnabled(novo);
    JbSalvar.setEnabled(salvar);
    JbEditar.setEnabled(editar);
    JbCancelar.setEnabled(cancelar);
    JbExcluir.setEnabled(excluir);
  }

  /**
   * Define se os JTextFields serão liberados para edição do usuário
   *
   * @param tf <b>True</b> - Habilitar; <b>False</b> - Desabilitar;
   */
  public void habilitaJtf(Boolean tf) {
    jtfIdProduto.setEnabled(tf);
    jtfQuantidade.setEnabled(tf);
    jtfObservacao.setEnabled(tf);
  }

  public void habilitaEdicaoVinculado(Boolean tf) {
    jtfIdProdutoVinculado.setEnabled(tf);
    jtfFator.setEnabled(tf);
  }

  private void editar() {
    habilitaJb(false, true, false, true, false);
    habilitaJtf(true);
    jtfIdProduto.requestFocus();
  }

  private void excluir() {
    try {
      control.excluir(criaObjeto());
      listar();
      limpar();
    } catch (ControllerException e) {
      Util.msgErro(e);
    }
  }

  private void cancelar() {
    limpar();
    habilitaJb(true, false, false, false, false);
    habilitaJtf(false);
    if (control.modoConsulta) {
      control.modoConsulta = false;
    } else {
      listar();
    }
  }

  private void selecionaRegistro() {
    int linha = jtCotacaoLancamento.getSelectedRow();
    int linhaSel = jtCotacaoLancamento.convertRowIndexToModel(linha);
    idPesquisa.setText(cotacaoLancamentoTm.getValueAt(linhaSel, CotacaoLancamentoTableModel.COLUNA_COD_ID).toString());
    modoConsultaExt = false;
    this.dispose();
  }

  private Boolean argFiltroInicioIsNull() {
    if (filtroEmpresa == null || filtroCliente == null) {
      Util.msgAdv("A empresa ou o cliente não foi selecionado");
      return true;
    }
    if (filtroCotacao == null) {
      Util.msgAdv("Não foi selecionada uma cotação");
      return true;
    } else {
      return false;
    }
  }

  private void filtroInicio() {
    if (!argFiltroInicioIsNull()) {
      jtfIdEmpresa.setEnabled(false);
      jtfIdCliente.setEnabled(false);
      jtfIdCotacao.setEditable(false);
      jbFiltrar.setEnabled(false);

      numLancamento = control.ultimoNumLancamento();
      listar();
      habilitaJb(true, false, false, false, false);
      habilitaJtf(true);
      novo();
    }
  }

  private void habilitaSelectCotacao() {
    if (jtfIdEmpresa.getText().isEmpty()) {
      jtfIdEmpresa.requestFocus();
    } else if (jtfIdCliente.getText().isEmpty()) {
      jtfIdCliente.requestFocus();
    } else if ((!jtfIdCliente.getText().isEmpty()
            && !jtfIdEmpresa.getText().isEmpty())
            || jtfIdCotacao.getText().isEmpty()) {
      jtfIdCotacao.setEnabled(true);
      jtfIdCotacao.requestFocus();
    } else if ((!jtfIdCliente.getText().isEmpty()
            && !jtfIdEmpresa.getText().isEmpty())
            && !jtfIdCotacao.getText().isEmpty()) {
      jbFiltrar.requestFocus();
    } else {
      jbFiltrar.requestFocus();
    }
  }

  private void carregaEmpresa(JTextField jtfId, JTextField jtfName) {
    if (!jtfId.getText().isEmpty()) {
      int idEmpresa = Integer.parseInt(jtfId.getText());
      filtroEmpresa = control.carregaEmpresa(idEmpresa);
      jtfName.setText(filtroEmpresa.getRazao());
    }
  }

  private void carregaCliente(JTextField jtfId, JTextField jtfName) {
    if (!jtfId.getText().isEmpty()) {
      int idCliente = Integer.parseInt(jtfId.getText());
      filtroCliente = control.carregaCliente(idCliente);
      jtfName.setText(filtroCliente.getRazao());
    }
  }

  private void carregaCotacao(JTextField jtfid, JTextField jtfname) {
    if (!jtfid.getText().isEmpty()) {
      int idCotacao = Integer.parseInt(jtfid.getText());
      filtroCotacao = control.carregaCotacao(idCotacao);
      jtfname.setText(filtroCotacao.getDescricao());
    }
  }

  private void reiniciar() {
    limpar();
    removeAllJtable();
    limparFiltro();

    jtfIdEmpresa.setEnabled(true);
    jtfIdCliente.setEnabled(true);
    jtfIdCotacao.setEnabled(false);
    jtfIdCotacao.setEditable(true);
    jbFiltrar.setEnabled(true);
    jbNovo.setEnabled(false);

    jtfIdEmpresa.requestFocus();
  }

  class ThreadReport extends Thread {

    @Override
    public void run() {
      try {
        control.report();
      } catch (Exception ex) {
        JOptionPane.showMessageDialog(null, ex.getMessage());
      }
    }
  }
}
